package com.lemon.mybatis.config;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.lemon.mybatis.mapper.BaseMapper;
import com.lemon.mybatis.mapper.CommonMapper;
import com.lemon.mybatis.properties.MapperProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

import java.util.Properties;

/**
 * @param
 * @author lemon
 * @description
 * @return
 * @date 2019-08-17 17:16
 */
@Slf4j
@ConditionalOnExpression("${mapper.custom.enabled: false}")
@Configuration
// 由于MapperScannerConfigurer执行的比较早，所以必须有下面的注解
@AutoConfigureAfter(org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration.class)
// TODO 读取不到配置值
@EnableConfigurationProperties(MapperProperties.class)
public class MybatisAutoConfiguration {

    /**
     * @param
     * @return
     * @description @Autowired无法注入MapperProperties
     * @author lemon
     * @date 2019-08-17 21:08
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(MapperProperties mapperProperties) {
        Preconditions.checkArgument(StringUtils.isNotBlank(mapperProperties.getBasePackage()), "Scanner 'basePackage' is required");

        if (log.isDebugEnabled()) {
            log.debug("使用自定义Mapper扫描配置", JSON.toJSONString(mapperProperties));
        }

        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName(mapperProperties.getSqlSessionFactoryBeanName());
        mapperScannerConfigurer.setBasePackage(mapperProperties.getBasePackage());

        Properties properties = new Properties();
        // 特别注意，不要把BaseMapper放到 basePackage 中，也就是不能同其他Mapper一样被扫描到。
        properties.setProperty("mappers", BaseMapper.class.getName() + "," + CommonMapper.class.getName());
        properties.setProperty("notEmpty", Boolean.toString(mapperProperties.isNotEmpty()));

        if (StringUtils.isNotBlank(mapperProperties.getIdentity())) {
            properties.setProperty("identity", mapperProperties.getIdentity());
        }

        if (StringUtils.isNotBlank(mapperProperties.getOrder())) {
            properties.setProperty("order", mapperProperties.getOrder());
        }

        mapperScannerConfigurer.setProperties(properties);

        if (log.isDebugEnabled()) {
            log.debug("custom mapper scan config properties: {}", JSON.toJSONString(properties));
        }

        return mapperScannerConfigurer;
    }
}
